import type { Router } from 'vue-router'
import NProgress from '@/http/progress'
// import { loadEnv } from '@build/index'
import { useI18n } from '@/locales/useI18n'
import { title } from '@/layout/setting'

import { createPermissionGuard } from './permissionGuard'
import { createStoreGuard } from './storeGuard'

export default function setupRouterGuard(router: Router) {
  createPageGuard(router)
  createProgressGuard(router)
  createPermissionGuard(router)
  createStoreGuard(router)
}

function createPageGuard(router: Router) {
  const loadedPageMap = new Map<string, boolean>()

  router.beforeEach(async to => {
    to.meta.loaded = !!loadedPageMap.get(to.path)
    return true
  })

  router.afterEach(to => {
    loadedPageMap.set(to.path, true)
    return true
  })
}

export function createProgressGuard(router: Router) {
  const { t } = useI18n()
  router.beforeEach(async to => {
    if (to.meta.loaded) {
      return true
    }

    document.title = to.meta.title
      ? `${t(to.meta.title as string)} | ${title}`
      : title
    NProgress.start()
    return true
  })

  router.afterEach(async () => {
    NProgress.done()
    return true
  })
}